<?php
/**
 * Login script which ensures that the user can login 
 */
session_start();
include_once("../config.inc.php");
include_once (CMS_ROOT . 'content/lib/cms_loader.class.php');
if(isset($_POST['username']) && $_POST['password']){
    //$oDBInstance = Mysql_dbconnection::getInstance();
    //Prevent sql injection and xss 
    $sUser = $_POST['username'];
    $sUser = get_magic_quotes_gpc() ? stripslashes($sUser) : $sUser;
    $sUser = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($sUser) : mysql_escape_string($sUser);
    //$sUser     = $oDBInstance->getSQLValueString($_POST['username'],'string');
    //$sPassword = $oDBInstance->getSQLValueString($_POST['password'], 'defined');
 
    $sPassword = $_POST['password'];
    $sPassword = get_magic_quotes_gpc() ? stripslashes($sPassword) : $sPassword;
    $sPassword = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($sPassword) : mysql_escape_string($sPassword);
         
        if ($sUser != "" && $sPassword != "" && (strlen($sPassword)>1)){
            mysql_connect(DBHOST,DBUSER,DBPASSWORD) or die ('Keine Verbindng');
            mysql_select_db(DBNAME) or die  ('Keine Verbindng');
            //Uses a function which encrypts the password 
            $sHashPassword =passwordHash($sPassword);
            //Echo $sHashPassword;
            $result = mysql_query("SELECT password FROM bs_cms_user WHERE username='$sUser' and password = '$sHashPassword'");
            $count = mysql_num_rows($result);
            //$oDBInstance->query("SELECT password FROM bs_cms_user WHERE username=$sUser and password = '$sHashPassword'");
            //$aResult = $oDBInstance->fetch('array');
            //$count = count($aResult);
            if ($count ==1){
                //Echo " logged";
                
                if(!isset($_SESSION['username'])){
                    $_SESSION['username'] = $sUser;
                    $url = $_SERVER['HTTP_REFERER'];
                    header('Location: '.$url);    

                    }
          
            }else {
                echo "Wrong username or Password";
                sleep(3);
                }
            }
        }
        /**
         * Hashes the password with an salt and sha256 algorithm 
         * @param string password
         */
        function passwordHash($sPassword){
            $sPassword = str_split($sPassword,(strlen($sPassword)/2));
            $sPassword = hash('sha256', $sPassword[0].'Cz]#%1K|'.$sPassword[1]);
            return $sPassword;
        }   
        /**
         * Overwrites the autoload function and calls our function Loader::loadClass
         * @param $sClassName
         */
        function __autoload($sClassName){
        Loader::loadClass($sClassName);
    }
?>